/*
 * @Author: Zhengyu Xin
 * @Date: 2021-06-08 16:59:11
 * @LastEditTime: 2022-02-08 10:27:06
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \hbs\libs\wechat\base.js
 */
const fs = require('fs')
const path = require('path');
const Req = require('../tools/Tools').Req;
class WxBase {
  static Mode = { Basic: 0, Redis: 1 }
  constructor(appid, secret, mode = WxBase.Mode.Basic) {
    this.appid = appid,
      this.secret = secret;
    this.mode = mode;
  }

  /**
   * @description: 将数据写入到json文件中
   * @param {*} str
   * @param {*} name
   * @return {*}
   */
  writeJson(str, name = "data.json") {

    try {
      fs.writeFileSync(__dirname +"/cache"+ `/${name}`, JSON.stringify(str));
      return true;
    } catch (err) {
      return false;
    }

  }
  /**
    * @description: 将json文件读取出来
    * @param {*} str
    * @param {*} name
    * @return {*}
    */
  readJson(name = "data.json") {
    let url=__dirname +"/cache"+ `/${name}`;
    let exist=fs.existsSync(url);
    if(exist){
      var str = fs.readFileSync(url);
      str = JSON.parse(str);
      return str;
    }
    return false;
    
  }
  /**
 * @description: 获取AccessToken
 * @return {*}
 */
  async getAccessToken() {
    let token=await this.#readAccessToken();
    if(!token){
       token=await this.refreshAccessToken();
       await this.#writeAccessToken(token);
    };
    return token;
  }
  async refreshAccessToken() {
    let findUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.appid}&secret=${this.secret}`;
    let answer = await Req.get(findUrl).catch((e) => {
      console.log(e);
    });
    console.log(answer);
    answer=JSON.parse(answer);
    if(answer.access_token){
      return answer.access_token;
    };
    return answer;
  }
  async #writeAccessToken(token) {
      if(this.mode===WxBase.Mode.Redis){
       return true;
      }else{
        this.writeJson({token,date:new Date().getTime(),appid:this.appid},this.appid);
        return true;
      };
  }
  async #readAccessToken() {
     if(this.mode===WxBase.Mode.Redis){

     }else{
       let ans=this.readJson(this.appid);
       console.log(ans);
       if(ans){
            let time=ans.date;
            let now=new Date().getTime();
            return ((now-time)/1000)<6000?ans.token:false;
       };
       return ans;
     }
  }
  async sendNotice(template_id,touser,page,data){
     let token=await this.getAccessToken();
     console.log("111111"+token);
     let updata={
      template_id:template_id,
      touser:touser,
      page:page,
      data:data
     };
     let url=`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${token}`;
     let ans=Req.post(url,updata);
     return ans;
  }
}
module.exports = WxBase;